package org.red_cross_service.common.captcha;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import org.red_cross_service.common.anno.NoNeedToken;
import org.red_cross_service.common.response.Response;
import org.red_cross_service.utils.Base64Util;
import org.red_cross_service.utils.RedisUtil;
import org.red_cross_service.utils.uuid.IdUtils;

import jakarta.annotation.Resource;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码控制
 */
@RestController
@RequestMapping("/api/captchaImage")
@CrossOrigin
public class CaptchaController {

    public static final String CAPTCHA_CODE_KEY = "captchaCode";

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisUtil redisUtil;

    @NoNeedToken
    @GetMapping("")
    public Response getCaptchaImage(@RequestParam(value = "captchaType", required = false, defaultValue = "math") String captchaType,
                                    @RequestParam(value = "time", required = false, defaultValue = "180") Integer time) {
        // 保存验证码信息
        String uuid = IdUtils.fastSimpleUUID();
        String verifyKey = CAPTCHA_CODE_KEY + uuid;
        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        redisUtil.setCacheObject(verifyKey, code, time, TimeUnit.SECONDS);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return Response.error(e.getMessage());
        }
        return new Response().put("code", 200).put("uuid", uuid).put("img", Base64Util.encode(os.toByteArray()));
    }
    @NoNeedToken
    @GetMapping("/verify")
    public Response verify(@RequestParam(value = "uuid", required = false) String uuid,
                           @RequestParam(value = "code", required = false) String code) {
        String verifyKey = CAPTCHA_CODE_KEY + uuid;
        String captcha = redisUtil.getCacheObject(verifyKey);
        if (captcha == null) {
            return Response.success("验证码已失效");
        }
        redisUtil.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            return Response.success("验证码错误");
        }
        return Response.success("验证成功");
    }

}
